package com.szrt.zw.test.menu.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szrt.zw.test.menu.dto.EasyuiTreeNode;
import com.szrt.zw.test.menu.entity.MenuEntity;
import com.szrt.zw.test.menu.service.MenuService;



@Controller
@RequestMapping("/central/menu")
public class MenuController {
	
	
	@Autowired
	private MenuService service;
	
	
	
	/**
	 * http://localhost:8080/easyui1607/menu/init.do
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/init")
	public List<EasyuiTreeNode> initTree(Integer id){
		//设计方法  当前台发送ajax请求的时候  给够把tree传回去
		List<EasyuiTreeNode>  list  = new ArrayList<EasyuiTreeNode>();
		if(null == id){
			MenuEntity entity = service.findRootNode();
			
			
			EasyuiTreeNode  node = new EasyuiTreeNode();
			int counterChildren = service.checkLeaf(entity.getId());
			if(counterChildren>0){
				//说明还有孩子
				node.setState("closed");
				
			}
			node.setId(entity.getId());
			node.setText(entity.getMenuName());
			list.add(node);
		}else{
			List<MenuEntity> menus =service.findChildren(id);
			
			
			
			for(MenuEntity entity : menus){
				
				
				EasyuiTreeNode  node = new EasyuiTreeNode();
				
				Map<String,Object> attributes = new  HashMap<String,Object>();
				
				attributes.put("url", entity.getUrl());
				
				node.setAttributes(attributes);
				
				
				int counterChildren = service.checkLeaf(entity.getId());
				if(counterChildren>0){
					//说明还有孩子
					node.setState("closed");
					
				}
				node.setId(entity.getId());
				node.setText(entity.getMenuName());
				list.add(node);
			}
		}
		
		return list;
		
	}

}
